package OrderService

import (
	"context"
	"errors"
	"gdshop-back-end-go/client-api/app/request/OrderReq"
	"gdshop-back-end-go/client-api/app/response/OrderResp"
	"github.com/syyongx/php2go"
)

// 按分组创建订单，分组可以是店铺、可以是其他规则
// goodsActivityId = 活动ID，0 为自动选择最优活动，-1 为不使用
func DoCreateByGroup(ctx context.Context, goodsLists []*OrderReq.GoodsItem, memberId int, couponIds []int,
	goodsActivityId int) (*OrderResp.OrderItem, error) {
	createModel := OrderResp.OrderItem{}
	createModel.Goodss = ([]*OrderResp.Goodss)(nil)
	for _, item := range goodsLists {
		goodssItem, err := DoCreateOne(ctx, item, memberId)
		if err != nil {
			return nil, err
		}
		// 当前商家信息固定为自营
		createModel.StoreId = goodssItem.StoreId
		createModel.StoreName = getGoodsStoreName(goodssItem.StoreId)
		createModel.Goodss = append(createModel.Goodss, goodssItem)
	}
	if len(createModel.Goodss) > 1 && goodsActivityId == 0 {
		return nil, errors.New("购物车创建订单，请先分组好并确定活动ID之后执行 doCreateByGroup 方法")
	}
	// 活动 扣减 单个商品
	if len(createModel.Goodss) == 1 && goodsActivityId == 0 {
		// 先处理团购，单个商品时，createModel.Goodss = goodsLists ，所以可以直接取第一个
		if goodsLists[0].TuanMode > 0 {

		} else {
			// 普通模式
			// 从商品详情创建订单的，可以自动选择最优惠的活动
			err := goodsActivityByCreateByGroup(ctx, &createModel)
			if err != nil {
				return nil, err
			}
			// GroupId 自动处理完，内部设置
		}
	}
	if goodsActivityId > 0 {
		if len(createModel.Goodss) < 1 {
			return nil, errors.New("商品为空")
		}
		// 自行选择了活动，直接读取活动
		err := goodsActivityModelById(ctx, &createModel, goodsActivityId)
		if err != nil {
			return nil, err
		}
		createModel.GroupId = goodsActivityId
	}
	// 如果 goodsActivityId = -1 ，则是自营商品，不使用活动
	if goodsActivityId == -1 {
		createModel.GroupId = -1
	}
	// 可用 优惠券
	useCouponOrderSubs := []OrderReq.OrderSubCoupon{}
	tmpUseCouponOrderSubs, err := GetCreateAvailableUseCoupon(ctx, memberId, createModel.Goodss)
	//fmt.Println("可用优惠券 tmpUseCouponOrderSubs ")
	//g.Dump(tmpUseCouponOrderSubs)
	if err != nil {
		return nil, err
	}
	// 可用券过滤，按 member_coupon_id 过滤，只保留不重复的
	memberCouponIds := []int{}
	for _, item := range tmpUseCouponOrderSubs {
		if !php2go.InArray(item.MemberCouponId, memberCouponIds) {
			useCouponOrderSubs = append(useCouponOrderSubs, item)
			memberCouponIds = append(memberCouponIds, item.MemberCouponId)
		}
	}
	createModel.CouponNum = len(useCouponOrderSubs)

	createModel.OrderSubCoupons = useCouponOrderSubs
	// 如果选择了券，然而可用券数量小于选择的数量，报错
	/*if len(couponIds) > createModel.CouponNum {
		return nil, errors.New("优惠券不一致，请重新选择")
	}*/
	if createModel.CouponNum > 0 {
		if len(couponIds) > 0 {
			// 如果上送了优惠券，则进行优惠券判断
			if couponIds[0] != 0 {
				createModel.McId = couponIds[0]
				for _, item := range useCouponOrderSubs {
					if createModel.McId == item.MemberCouponId {
						// 目前只匹配第一张
						createModel.SelectCouponId = item.CouponId

						break
					}
				}

				if createModel.SelectCouponId == 0 {
					return nil, errors.New("优惠券无法匹配")
				}
			}
		} else {
			// 未上送
			// 取出最优的优惠券
			var zuiyouhui int64 = 0
			// 当前先设置每个订单只能使用一张券
			for _, item := range useCouponOrderSubs {
				if item.Discount > zuiyouhui {
					zuiyouhui = item.Discount
					createModel.SelectCouponId = item.CouponId
					createModel.McId = item.MemberCouponId
				}
			}
		}

		// 循环计算优惠
		for _, useCouponOrderSub := range useCouponOrderSubs {
			if createModel.McId != useCouponOrderSub.MemberCouponId {
				continue
			}
			for _, goods := range goodsLists {
				if useCouponOrderSub.GoodsOptionId == int(goods.GoodsOptionId) {
					createModel.DiscountMoney += useCouponOrderSub.Discount

				}
			}
			// 根据选中的优惠券，计算商品实付价格
			for _, gs := range createModel.Goodss {
				if gs.Options[0].Id == uint(useCouponOrderSub.GoodsOptionId) {
					gs.Paid = useCouponOrderSub.Paid
					gs.DiscountMoney = useCouponOrderSub.Discount
				}
			}
		}
	}

	// 计算总价
	var totalPrice int = 0
	for _, item := range createModel.Goodss {
		totalPrice += int(item.Options[0].SellPrice) * item.BuyNum
	}
	//createModel.TotalPrice = totalPrice - int(createModel.DiscountMoney)
	createModel.TotalPrice = totalPrice
	createModel.Freight = 0

	return &createModel, nil
}
